package com.jiang.server;

import com.jiang.Domain.Message;
import com.jiang.Domain.MessageType;
import com.jiang.utils.Utility;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * @author Jiang
 * @version 1.0
 * @date 2023/12/1 19:02
 */
public class SendNewsToAllService implements Runnable {

    @Override
    public void run() {
        while (true) {

            System.out.print("请输入服务器要推送的新闻[输入exit表示退出推送服务]：");
            String news = Utility.readString(100);
            if (news.equals("exit")) {
                break;
            }

            // 群发消息
            Message message = new Message();
            message.setSender("服务器");
            message.setContent(news);
            message.setSendTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
            message.setMesType(MessageType.MESSAGE_TO_ALL_MES);
            System.out.println("服务器推送消息给所有人 说：" + news);

            // 遍历所有的通信线程，并转发
            HashMap<String, ServerConnectClientThread> hm = ManageServerConnectClientThread.getHm();
            for (Map.Entry<String, ServerConnectClientThread> entry : hm.entrySet()) {
                ServerConnectClientThread thread = entry.getValue();
                try {
                    ObjectOutputStream objectOutputStream = new ObjectOutputStream(thread.getSocket().getOutputStream());
                    objectOutputStream.writeObject(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
